﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using umbraco;
using umbraco.BusinessLogic;

namespace TheOutfield.UmbExt.Backfire4Umbraco.Web
{
    public class BackfireFilter : Stream
    {
        public BackfireFilter(Stream stream)
        {
            _stream = stream;
        }

        private Stream _stream;

        #region Properties

        public override bool CanRead
        {
            get { return true; }
        }

        public override bool CanSeek
        {
            get { return true; }
        }

        public override bool CanWrite
        {
            get { return true; }
        }

        #endregion

        #region Methods

        public override void Flush()
        {
            _stream.Flush();
        }

        public override long Length
        {
            get { return 0; }
        }

        private long _position;
        public override long Position
        {
            get { return _position; }
            set { _position = value; }
        }

        public override int Read(byte[] buffer, int offset, int count)
        {
            return _stream.Read(buffer, offset, count);
        }

        public override long Seek(long offset, SeekOrigin origin)
        {
            return _stream.Seek(offset, origin);
        }

        public override void SetLength(long value)
        {
            _stream.SetLength(value);
        }

        public override void Close()
        {
            _stream.Close();
        }

        public override void Write(byte[] buffer, int offset, int count)
        {
            byte[] data = new byte[count];
            Buffer.BlockCopy(buffer, offset, data, 0, count);
            string html = Encoding.Default.GetString(buffer);

            if (!html.Contains("bf4u.js"))
            {
                html = html.Replace("</head>", "<script type='text/javascript' src='/umbraco/plugins/theoutfield/backfire4umbraco/bf4u.js'></script></head>");
            }

            byte[] outdata = Encoding.Default.GetBytes(html);
            _stream.Write(outdata, 0, outdata.GetLength(0));
        }

        #endregion
    }
}